﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

namespace Nirvana
{
    public sealed class WaitLoadFileInfo : CustomYieldInstruction
    {
        private AssetBundleInfo abInfo;
        private UnityWebRequest webRequest;
        private AsyncOperation ayncOper;
        public string Error { get; private set; }
        public AssetBundleInfo FileInfo
        {
            get { return this.abInfo; }
        }
        public WaitLoadFileInfo(AssetBundleInfo abInfo)
        {
            this.abInfo = abInfo;
        }
        public WaitLoadFileInfo(AssetBundleInfo abInfo, UnityWebRequest webRequest, AsyncOperation ayncOper)
        {
            this.abInfo = abInfo;
            this.webRequest = webRequest;
            this.ayncOper = ayncOper;
        }
        public override bool keepWaiting
        {
            get
            {
                if (this.abInfo.IsHaveToken())
                {
                    return false;
                }

                if (!this.ayncOper.isDone) return true;
                this.abInfo.Clear();
                if (this.webRequest.isNetworkError)
                {
                    this.Error = this.webRequest.error;
                    this.webRequest.Dispose();
                    this.webRequest = null;
                    return false;
                }
                if(this.webRequest.isHttpError || this.webRequest.responseCode < 0 || this.webRequest.responseCode >= 400)
                {
                    this.Error = string.Format("Http error code: {0}", this.webRequest.responseCode);
                    this.webRequest.Dispose();
                    this.webRequest = null;
                    return false;
                }
                string content = DownloadHandlerBuffer.GetContent(this.webRequest);
                this.webRequest.Dispose();
                this.webRequest = null;
                if (!this.abInfo.ParseToken(content))
                {
                    this.Error = "Parse file info file failed.";
                }
                return false;
            }
        }
    }
}


